﻿using Sidvall.UI.Dialogs;
using System;
using System.Threading.Tasks;
using Windows.Storage.Pickers;

namespace Sidvall.UI.Uwp.Dialogs
{
    public class FileDialog : IFileDialog
    {
        #region Public Members

        #region OpenFilesAsync

        public async Task OpenFilesAsync(OpenFileDialogContext context)
        {
            if (context == null)
                throw new System.ArgumentNullException(nameof(context));

            this.Context = context;
            var dialog = new FileOpenPicker();
            var filters = context.FileTypeChoices.GetFileTypeFilters();
            foreach (var filter in filters)
            {
                if (!filter.Contains("*"))
                    dialog.FileTypeFilter.Add(filter);
            }
            dialog.SuggestedStartLocation = PickerManager.GetPickerLocationId(context.InitialFolder);
            dialog.ViewMode = PickerManager.GetPickerViewMode(null);
            if (this.Context.AllowMultipleSelect)
            {
                var files = await dialog.PickMultipleFilesAsync();
                if (files != null)
                {
                    foreach (var file in files)
                        this.Context.FileNames.Add(file.Path);
                }
            }
            else
            {
                var file = await dialog.PickSingleFileAsync();
                if (file != null)
                    this.Context.FileName = "?" + Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(file);
                else
                    this.Context.FileName = null;
            }
        }

        #endregion
        #region SaveFileAsync

        public async Task SaveFileAsync(SaveFileDialogContext context)
        {
            if (context == null)
                throw new System.ArgumentNullException(nameof(context));

            var dialog = new FileSavePicker();
            dialog.SuggestedStartLocation = PickerManager.GetPickerLocationId(context.InitialFolder);
            foreach (var fileTypeChoice in context.FileTypeChoices)
                dialog.FileTypeChoices.Add(fileTypeChoice.Name, fileTypeChoice.FileTypeFilter);
            var file = await dialog.PickSaveFileAsync();
            if (file != null)
                context.FileName = "?" + Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(file);
            else
                context.FileName = null;
        }

        #endregion

        #endregion
        #region Private Members

        private OpenFileDialogContext Context { get; set; }

        #endregion
    }
}
